# -*- coding: utf-8 -*-
from src       import utils
from src.types import RegionType

from fastapi           import Request, APIRouter, HTTPException
from fastapi.responses import Response, JSONResponse


region_types = APIRouter(prefix = "/types", dependencies = [utils.check.has_auth()])


@region_types.get("/array")
async def regions_get(request: Request):
    database = request.app.database

    cursor = await database.execute("SELECT * FROM region_types")
    result = await cursor.fetchall()
    column = ('id', 'name')

    region_types = []

    for region_type in result:
        dictionary = {}

        for index, value in enumerate(region_type):
            dictionary[column[index]] = value
        
        region_types.append(dictionary)

    return JSONResponse(region_types, status_code = 200)


@region_types.get("/{typeId}")
async def region_types_get(request: Request, typeId: int):
    if typeId == None or 0 >= typeId:
        raise HTTPException(400, detail = "Invalid ID")

    region_type = await RegionType.get_by(request.app.database, id = typeId)

    if not region_type:
        raise HTTPException(404, detail = "The region type with this ID was not found")
    return JSONResponse(region_type("id", "name"), status_code = 200)


@region_types.post("/")
async def region_types_add(request: Request):
    data: dict = await utils.parse.dictionary(request = request)

    if not data:
        raise HTTPException(400, detail = "Failed to get passed values, specify them in JSON format")

    if ("name" not in data) or (data["name"].strip() == ""):
        raise HTTPException(400, detail = f"No values found: name")

    database = request.app.database
    exists   = await RegionType.exists(database, name = data["name"])

    if exists:
        raise HTTPException(409, detail = 'An region type with this ID already exists')

    region_type = await RegionType.create(database, **data)
    return JSONResponse(region_type("id", "name"), status_code = 201)


@region_types.put("/{typeId}")
async def region_types_change(request: Request, typeId: int):
    if typeId == None or 0 >= typeId:
        raise HTTPException(400, detail = "Invalid ID")

    data = await utils.parse.dictionary(request)

    if not data:
        raise HTTPException(400, detail = "Failed to get passed values, specify them in JSON format")

    region_type = await RegionType.get_by(request.app.database, id = typeId)

    if not region_type:
        raise HTTPException(404, detail = "The region type with this ID was not found")

    if ("name" not in data) or (data["name"].strip() == ""):
        raise HTTPException(400, detail = "Invalid name")

    if region_type.name != data["name"]:
        exists = await region_type.exists(name = data["name"])

        if exists:
            raise HTTPException(409, detail = 'An region type with this ID already exists')

    await region_type.update(**data)
    return JSONResponse(region_type("id", "name"), status_code = 200)


@region_types.delete("/{typeId}")
async def region_types_delete(request: Request, typeId: int):
    if typeId == None or 0 >= typeId:
        raise HTTPException(400, detail = "Invalid ID")

    region_type = await RegionType.get_by(request.app.database, id = typeId)

    if not region_type:
        raise HTTPException(404, detail = "The region type with this ID was not found")

    await region_type.delete()
    return Response(None)
